package mail

import (
	"card/pkg/config"
	"card/pkg/logger"
	"card/pkg/util"
	"context"
	"crypto/tls"
	"fmt"
	"net/smtp"

	emailPKG "github.com/jordan-wright/email"
)

// SMTP 实现 email.Driver interface
type SMTP struct {
	ctx context.Context
}

func NewSmtp(ctx context.Context) *SMTP {
	return &SMTP{ctx: ctx}
}

// Send 实现 email.Driver interface 的 Send 方法
func (s *SMTP) Send(email Email) bool {
	e := emailPKG.NewEmail()
	smtpInfo := config.GetStringMapString("mail.smtp")
	fromEmailInfo := config.GetStringMapString("mail.from")
	e.From = fmt.Sprintf("%v <%v>", fromEmailInfo["name"], fromEmailInfo["address"])
	e.To = email.To
	e.Bcc = email.Bcc
	e.Cc = email.Cc
	e.Subject = email.Subject
	e.Text = email.Text
	e.HTML = email.HTML
	var err error
	for _, v := range email.Files {
		if !util.FileExist(v) {
			logger.ErrorString(s.ctx, "[发送邮件]", "email", fmt.Sprintf("%s文件不存在", v))
			return false
		}
	}
	if smtpInfo["encryption"] == "ssl" {
		err = e.SendWithTLS(
			fmt.Sprintf("%v:%v", smtpInfo["host"], smtpInfo["port"]),
			smtp.PlainAuth(
				"",
				smtpInfo["username"],
				smtpInfo["password"],
				smtpInfo["host"],
			),
			&tls.Config{
				InsecureSkipVerify: true,
				ServerName:         smtpInfo["host"],
			},
		)
	} else {
		err = e.Send(
			fmt.Sprintf("%v:%v", smtpInfo["host"], smtpInfo["port"]),
			smtp.PlainAuth(
				"",
				smtpInfo["username"],
				smtpInfo["password"],
				smtpInfo["host"],
			),
		)
	}
	if err != nil {
		logger.ErrorString(s.ctx, "[发送邮件]", "email", err.Error())
		return false
	}
	return true
}
